/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication2;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 *
 * @author max
 */
public class JavaApplication2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException, SQLException {
        // TODO code application logic here
        String server = "172.16.125.67"; //args[0]; //ip-аддрес сервера db
        String user = "enterprisedb"; //args[1]; //логин db
        String pass = "Ufufhby1961"; //args[2]; //пароль db
        String db = "minsport"; //args[3]; //используемая база
        String folderconf = "/home/max"; // args[4]; //папка к запускаемой конфигурации jboss
        String sql = "SELECT file_store_url FROM card WHERE file_store_url IS NOT NULL group by card_id, file_name, file_store_url";
        
        //----------------------------------------------------------------------
        //чтение файла настроек и выдергивание пути до хранилища
        String path = folderconf + "/solr/conf/solrModule.properties"; //"/conf/dbmi/solr/solrModule.properties"; //путь до настроек хранилища
        
        FileReader file = new FileReader(path);
        Scanner text = new Scanner(file);
        String folderstore = null;
        while (text.hasNext()) {
            String print = text.nextLine();
            if (print.contains("store.rootLocation=")) {
                folderstore = print.replace("store.rootLocation=", "");
            }
        }
        System.out.println("folderstore - " + folderstore);
        text.close();
        
        //----------------------------------------------------------------------
        //выполнение поиска файлов в хранилище
        ProcessBuilder proc = new ProcessBuilder("find", folderstore, "-type", "f");
        
        Process proces = proc.start();
        
        InputStream stdout = proces.getInputStream();
        InputStreamReader isr = new InputStreamReader(stdout);
        BufferedReader br = new BufferedReader(isr);
        
        List<String> listfolder = new ArrayList<String>();
        String line = null;
        while ((line = br.readLine()) != null) {
            String ln = line;
            listfolder.add(ln);
        }
        
        int exit = proces.waitFor();
        
        System.out.println("listfolder - " + listfolder);
        
        //----------------------------------------------------------------------
        //подключение к базе и выдергивание данных о файлах в базе
        Class.forName("org.postgresql.Driver");
        String url = "jdbc:postgresql://"+server+"/"+db;
        Connection connection = DriverManager.getConnection(url, user, pass);
        Statement stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        
        List<String> listdb = new ArrayList<String>();
        while (rs.next()) {
            String orig = rs.getString("file_store_url");
            String repl = orig.replace("filestore:$filestorage/./", "/");
            listdb.add(repl);
        }
        System.out.println("listdb - " + listdb);
        
        //----------------------------------------------------------------------
        //подсчет количества файлов без ссылок
        int summ = 0;
        boolean check;
        for (int y = 0; y < listfolder.size(); y++) {
            check = false;
            for (int i = 0; i < listdb.size(); i++) {
                if (listfolder.get(y).contains(listdb.get(i))) {
                    check = true;
                }
            }
            if (check) {
                summ++;
            }
        }
        
        System.out.println(summ);
    }
}
